package com.demo2do.fms.admin.dao.business;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.demo2do.core.persistence.GenericJdbcSupport;
import com.demo2do.core.utils.DateFormatUtils;
import com.demo2do.fms.entity.business.Sequences;

/**
 *
 * @author Ark
 *
 */
@Repository("sequenceDaoSupport")
public class SequenceDaoSupport {
    
    private static final Logger logger = LoggerFactory.getLogger(SequenceDaoSupport.class);
    
    @Autowired
    private GenericJdbcSupport genericJdbcSupport;
    
    /**
     * get sap sequence by type
     * 
     * @param type
     * @return
     */
    public String getSapSequence(String type) {
        
        // 1. 获取sequence_code值
        // TODO  temp remove FOR UPDATE
        String searchSentence = "SELECT sequence_code AS code  FROM tbl_all_sequence WHERE type = :type";
        Map<String, Object> result = genericJdbcSupport.queryForObject(searchSentence, "type", type);
        BigDecimal sequenceCode = (BigDecimal) result.get("code");
        long code = sequenceCode.longValue();
        
        // 2. 判断code值
        code = (code == 999) ? 0 : code + 1;
        
        // 3. 更新code值
        String updateSentence = "UPDATE tbl_all_sequence SET sequence_code = :sequence WHERE type = :type";
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("sequence", code);
        parameters.put("type", type);
        genericJdbcSupport.executeSQL(updateSentence, parameters);
        
        // 4. 返回code
        return String.valueOf(code);
        
    }
    
    /**
     * @param type
     * @param condition
     * @return
     */
    public String getDispatchOrderSequence(String type, String condition) {
        
        String sentence = "SELECT sequence_code AS code FROM tbl_all_sequence WHERE type = :type AND condition = :condition";
        
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("type", type);
        parameters.put("condition", condition);
        
        Map<String, Object> result = genericJdbcSupport.queryForObject(sentence, parameters);
        
        if(result != null && !result.isEmpty()) {
        	
        	BigDecimal sequenceCode = (BigDecimal) result.get("code");
            logger.info("#getDispatchOrderSequence() - sequence code is [{}]", sentence.toString());
            
            return sequenceCode.toString();
        }
        
        return null;
                
    }
    
    /**
     * @param type
     * @param condition
     * @param sequenceCode
     */
    public void updateDispatchOrderSequence(String type, String condition, String sequenceCode) {
        
        String sentence = "UPDATE tbl_all_sequence SET sequence_code = :sequenceCode WHERE type = :type AND condition = :condition";
        
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("type", type);
        parameters.put("condition", condition);
        parameters.put("sequenceCode", sequenceCode);
        
        genericJdbcSupport.executeSQL(sentence, parameters);
        
    }
    
    /**
     * 
     * @param companyCode
     * @param type
     * @return
     */
    public String getSequence(String companyCode, String type) {
        
        String condition = DateFormatUtils.format(new Date(), "yyyyMM");
        
        // TODO temp remove FOR UPDATE
        String sentence = "SELECT * FROM tbl_all_sequence WHERE type = :type AND condition= :condition AND company_code = :companyCode";
        
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("type", type);
        parameters.put("condition", condition);
        parameters.put("companyCode", companyCode);
        
        Sequences sequence = genericJdbcSupport.queryForObject(sentence, parameters, Sequences.class);
        
        if (sequence == null) {
            
            String insertSentence = "INSERT INTO TBL_ALL_SEQUENCE(id, type, sequence_code, condition, company_code) VALUES (HIBERNATE_SEQUENCE.NEXTVAL, :type, :sequenceCode, :condition, :companyCode)";
            sequence = new Sequences(type, 1L, condition, companyCode);
            genericJdbcSupport.executeSQL(insertSentence, sequence);
            
        } else {            // increase sequence
            
            String updateSentence = "UPDATE tbl_all_sequence SET sequence_code = :sequenceCode WHERE id = :id";
            Map<String, Object> updateParameters = new HashMap<String, Object>();
            updateParameters.put("sequenceCode", sequence.getSequenceCode() + 1L);
            updateParameters.put("id", sequence.getId());
            genericJdbcSupport.executeSQL(updateSentence, updateParameters);
            
        }
        
        String result = "000000" + sequence.getSequenceCode().toString();
        return companyCode + condition + result.substring(result.length() - "000000".length(), result.length());
        
    }
    
}